# -*- coding: utf-8 -*-
# standard
import os
import sys

# third

# local
_P_PATH =  os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if _P_PATH not in sys.path:
    sys.path.append(_P_PATH)
from models import *


"""
@Title:   
@File: iot_func.py
@Author: walle 2025年08月27日 16时44分36秒
@Version: 1.0.0
@Desc: 
"""


def alert_summary_group_by_priority_sync(customer_ids: List[int] | None = None,
                                                store_ids: List[int] | None = None,
                                                not_recovery: int | None = None,
                                                days: int = 3) -> Resp:
    """
    获取告警统计信息，按严重程度分组
    :param customer_ids: _description_, defaults to None
    :param store_ids: _description_, defaults to None
    :param not_recovery: 是否只查询未恢复的事件，1是，0否，, defaults to None
    :param days: 查询往前几天的事件, defaults to 3
    :return: _description_
    """
    db_session, resp = new_db_session(), Resp()
    s = select(
        func.coalesce(func.count(InFluxDBAlertOrm.id), 0),
        InFluxDBAlertOrm.priority,
    ).where(
        InFluxDBAlertOrm.alert_time >= datetime.now() - timedelta(days=days)
    )
    if customer_ids:
        s = s.where(InFluxDBAlertOrm.customer_id.in_(customer_ids))
    if store_ids:
        s = s.where(InFluxDBAlertOrm.store_id.in_(store_ids))
    if not_recovery:
        if not_recovery == 1:
            s = s.where(InFluxDBAlertOrm.recovery_time == None)
        else:
            s = s.where(InFluxDBAlertOrm.recovery_time != None)
    s = s.group_by(InFluxDBAlertOrm.priority)
    query = db_session.execute(s)
    result = query.fetchall()
    db_session.close()
    data = {
        "alert": 0,
        "warning": 0,
    }
    for r in result:
        if r[1] == EventPriority.WARNING.value:
            data['warning'] += r[0]
        elif r[1] == EventPriority.ALERT.value:
            data['alert'] += r[0]
        elif r[1] is None:
            pass
        else:
            logger.error(f"unknown priority: {r[1]}")
    resp.data = data
    return resp


if __name__ == '__main__':
    pass